<template>
  <div class="app-container">
    <el-card class="tableset" shadow="never" :body-style="{ padding: '0px' }">
      <div>
        <span class="title">优惠券活动管理</span>
        <el-button
          type="primary"
          class="title-button-right"
          icon="el-icon-plus"
          plain
          @click="openAddDiscountCouponActivityDialog"
        >新增活动信息</el-button>
      </div>

      <!-- 搜索关键词 -->
      <div class="funtion">
        <el-input
          v-model="get_discount_coupon_activity_info_list.keyword"
          placeholder="请输入关键词"
          class="input-with-select"
          clearable
          @keyup.enter.native="getDiscountCouponActivityInfoList"
        >
          <el-select
            slot="prepend"
            v-model="get_discount_coupon_activity_info_list.keywordType"
            placeholder="请选择"
            class="option"
          >
            <el-option label="活动标题" :value="0" />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="getDiscountCouponActivityInfoList" />
        </el-input>
      </div>
      <!-- 搜索关键词 -->

      <!-- 数据表 -->
      <el-table
        v-loading="dataRequestLoading"
        element-loading-text="正在加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        :data="data_discount_coupon_activity_info_list.data"
        class="table"
        highlight-current-row
        style="width: 100%;"
        :height="tableHeight"
        :max-height="tableHeight"
        @sort-change="changeSort"
        @filter-change="changefilter"
        @selection-change="getSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          :filters="data_discount_coupon_activity_info_list.filterArea"
          :filter-multiple="false"
          column-key="areaId"
          prop="title"
          label="所在区域"
        >
          <template slot-scope="{ row }">
            <span>{{ '['+row.area_number+'] '+row.area_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="活动标题" />
        <el-table-column label="活动封面图">
          <template slot-scope="{ row }">
            <el-image :src="getPath() + row.cover_path" style="width:60px;height:60px" fit="scale-down" :preview-src-list="[getPath() + row.cover_path]" />
          </template>
        </el-table-column>
        <el-table-column :filters="filterConditionType" :filter-multiple="false" column-key="filterConditionType" label="触发条件">
          <template slot-scope="{ row }">
            <span>{{ condition_type[row.condition_type] }}</span>
          </template>
        </el-table-column>
        <el-table-column :filters="[{ text: '隐藏', value: 0 }, { text: '显示', value: 1 }]" :filter-multiple="false" column-key="filterIsShow" label="是否显示">
          <template slot-scope="{ row }">
            <span>{{ is_show[row.is_show] }}</span>
          </template>
        </el-table-column>
        <el-table-column :filters="filterStatus" :filter-multiple="false" column-key="filterStatus" prop="status" label="活动状态">
          <template slot-scope="{ row }">
            <el-tag :type="status_color(row.status)" effect="dark">{{ status_text(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="发布时间" sortable="custom" column-key="create_time" />
        <el-table-column fixed="right" label="操作" width="210px">
          <template slot-scope="{ row }">
            <el-button type="primary" @click.stop="openEditDiscountCouponActivityDialog(row)">编辑</el-button>
            <el-button type="success" @click.stop="openDiscountCouponInventoryDialog(row)">优惠券库存管理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据表 -->

      <!-- 数据表左下方功能区 -->
      <div>
        <el-button
          type="danger"
          class="card-bottom-button-left"
          icon="el-icon-delete"
          plain
          :disabled="notShowDisabled"
          @click="deleteDiscountCouponInfo()"
        >删除</el-button>
        <el-button
          type="success"
          class="card-bottom-button-left"
          icon="el-icon-check"
          plain
          :disabled="showDisabled"
          @click="changeDiscountCouponActivityShow(1)"
        >显示</el-button>
        <el-button
          type="warning"
          class="card-bottom-button-left"
          icon="el-icon-minus"
          plain
          :disabled="notShowDisabled"
          @click="changeDiscountCouponActivityShow(0)"
        >隐藏</el-button>
      </div>
      <!-- 数据表左下方功能区 -->

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="total, sizes,prev, pager, next, jumper"
        :total="data_discount_coupon_activity_info_list.total"
        :page-size="get_discount_coupon_activity_info_list.pageSize"
        :page-sizes="[20, 50, 100]"
        :current-page="get_discount_coupon_activity_info_list.currentPage"
        @size-change="changePageSize"
        @current-change="changeCurrentPage"
      />
      <!-- 分页 -->
    </el-card>

    <!-- 新增/修改活动信息dialog -->
    <el-dialog
      :title="change_discount_coupon_activity_info_title"
      :visible.sync="changeDiscountCouponActivityDialog"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-alert
        title="简介与规则编写注意"
        type="warning"
        description="1. 受信任的HTML节点有a、abbr、b、blockquote、br、code、col（span，width）、colgroup（span，width）、dd、del、div、dl、dt、em、fieldset、h1~h6、hr、i、img（alt，src，height，width）、ins、label、legend、li、ol、p、q、span、strong、sub、sup、table（width）、tbody、td（colspan，height，rowspan，width）、tfoot、th（colspan，height，rowspan，width）、thead、tr、ul
                    2. 全局支持class和style属性，不支持id属性。
                    3. 不推荐使用 String 类型，性能会有所下降
                    4. 屏蔽所有节点的事件
                    5. img 标签仅支持网络图片"
        show-icon
        :closable="false"
      />
      <el-divider content-position="left">优惠活动信息</el-divider>
      <el-form
        v-if="change_discount_coupon_activity_info_title === '修改活动信息'"
        :inline="true"
        label-width="110px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属区域编号">
              <span>{{ change_discount_coupon_activity_info.area_number }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域">
              <span>{{ change_discount_coupon_activity_info.area_name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        v-if="change_discount_coupon_activity_info_title === '新增活动信息'"
        ref="changeDiscountCouponActivityRulesForm1"
        :model="change_discount_coupon_activity_info"
        status-icon
        label-width="110px"
      >
        <el-form-item prop="area_id" :rules="rules.select" label="所属区域">
          <el-select v-model="change_discount_coupon_activity_info.area_id" placeholder="请选择所属区域">
            <el-option
              v-for="item in data_discount_coupon_activity_info_list.area"
              :key="item.area_id"
              :label="item.name"
              :value="item.area_id"
            >
              <span style="float: left;margin-right: 0.5rem">{{ item.area_number }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        ref="changeDiscountCouponActivityRulesForm2"
        :model="change_discount_coupon_activity_info"
        status-icon
        :inline="true"
        label-width="110px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="title" :rules="rules.input" label="活动标题">
              <el-input v-model="change_discount_coupon_activity_info.title" placeholder="请输入活动标题" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="change_discount_coupon_activity_info_title === '修改活动信息'" label="活动触发条件">
              <span>{{ condition_type[change_discount_coupon_activity_info.condition_type] }}</span>
            </el-form-item>
            <el-form-item v-if="change_discount_coupon_activity_info_title === '新增活动信息'" prop="condition_type" :rules="rules.select" label="活动触发条件">
              <el-select v-model="change_discount_coupon_activity_info.condition_type" placeholder="请选择活动触发条件">
                <el-option
                  v-for="item in condition_type_select"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        ref="changeDiscountCouponActivityRulesForm3"
        :model="change_discount_coupon_activity_info"
        status-icon
        :inline="true"
        label-width="110px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示/隐藏">
              <el-radio-group v-model="change_discount_coupon_activity_info.is_show">
                <el-radio-button :label="1">显示</el-radio-button>
                <el-radio-button :label="0">隐藏</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status" :rules="rules.select" label="活动状态">
              <el-select v-model="change_discount_coupon_activity_info.status" placeholder="请选择">
                <el-option
                  v-for="item in status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form v-if="change_discount_coupon_activity_info_title === '修改活动信息'" :inline="true" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间">
              <span>{{ change_discount_coupon_activity_info.start_date }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <span>{{ change_discount_coupon_activity_info.end_date }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        v-if="change_discount_coupon_activity_info_title === '新增活动信息'"
        ref="changeDiscountCouponActivityRulesForm4"
        :model="change_discount_coupon_activity_info"
        status-icon
        label-width="110px"
      >
        <el-form-item prop="end_date" :rules="rules.select" label="活动期限">
          <el-date-picker
            v-model="datePicker"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changePickTime"
          />
        </el-form-item>
      </el-form>
      <el-form
        ref="changeDiscountCouponActivityRulesForm5"
        :model="change_discount_coupon_activity_info"
        status-icon
        label-width="110px"
      >
        <el-form-item v-if="change_discount_coupon_activity_info_title === '修改活动信息'" label="活动发布时间">
          <span>{{ change_discount_coupon_activity_info.create_time }}</span>
        </el-form-item>
        <el-form-item prop="intro" :rules="rules.input" label="活动简介">
          <el-input v-model="change_discount_coupon_activity_info.intro" type="textarea" :autosize="{ minRows: 4, maxRows: 4}" placeholder="请输入活动规则" clearable />
        </el-form-item>
        <el-form-item prop="rule" :rules="rules.input" label="活动规则">
          <el-input v-model="change_discount_coupon_activity_info.rule" type="textarea" :autosize="{ minRows: 4, maxRows: 4}" placeholder="请输入活动规则" clearable />
        </el-form-item>
      </el-form>
      <el-form
        ref="changeDiscountCouponActivityRulesForm6"
        :model="change_discount_coupon_activity_info"
        status-icon
        :inline="true"
        label-width="110px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="path" :rules="rules.image" label="活动封面图">
              <el-upload
                class="avatar-uploader"
                action
                :show-file-list="false"
                :auto-upload="false"
                :on-change="changeCoverUploadImage"
              >
                <img v-if="change_discount_coupon_activity_info.cover_path" :src="show_cover_path" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="path" :rules="rules.image" label="活动背景图">
              <el-upload
                class="avatar-uploader"
                action
                :show-file-list="false"
                :auto-upload="false"
                :on-change="changeUploadImage"
              >
                <img v-if="change_discount_coupon_activity_info.path" :src="show_path" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        ref="changeDiscountCouponActivityRulesForm5"
        :model="change_discount_coupon_activity_info"
        status-icon
        label-width="110px"
      >
        <el-form-item prop="coupon_color" :rules="rules.select" label="优惠券背景颜色">
          <el-color-picker v-model="change_discount_coupon_activity_info.coupon_color" />
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button type="primary" icon="el-icon-plus" @click="addDiscountCouponTemplateInnerDialog = true">添加优惠券模板</el-button>
      </div>
      <el-divider content-position="left">优惠券模板信息</el-divider>
      <span v-for="(item, index) in bug" :key="`ad${index}`">{{ item.ad }}</span>
      <el-card v-for="(item, index) in data_discount_coupon_template" :key="index" shadow="hover">
        <el-row>
          <el-col :span="12">
            <span>{{ item.name+' - '+item.subhead }}</span>
            <span>{{ '（'+type[item.type]+'）' }}</span>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <span>{{ item.discount_coupon_template_number }}</span>
          </el-col>
        </el-row>
        <el-divider />
        <h3 v-if="item.type === 0">{{ '￥ '+item.subtract_price+' 优惠券' }}<span v-if="item.user_type === 0">{{ '（'+user_type[item.user_type]+'专享）' }}</span></h3>
        <h3 v-if="item.type === 1">{{ item.discount+' 折' }}<span v-if="item.user_type === 0">{{ '（'+user_type[item.user_type]+'专享）' }}</span></h3>
        <span>{{ '订单满 '+item.full_price+' 元' }}</span><br>
        <span v-if="item.surplus_num !== undefined">{{ '库存剩余 '+item.surplus_num+' 张' }}</span>
        <span v-else>{{ '库存剩余 0 张' }}</span>
        <div style="text-align: right;">
          <span v-if="item.is_fixed_date === 0">{{ '自领取日起 '+item.expiry_day+' 天' }}</span>
          <span v-if="item.is_fixed_date === 1">{{ item.commencement_date+' - '+item.expiry_date }}</span><br>
          <el-button v-if="data_discount_coupon_template.length > 1" type="text" @click="localDeleteDiscountCouponTemplate(item)">删除</el-button>
          <el-button v-else type="text" :disabled="true">删除</el-button>
        </div>
      </el-card>
      <el-dialog
        width="800px"
        title="请选择要添加的优惠券模板"
        :visible.sync="addDiscountCouponTemplateInnerDialog"
        append-to-body
      >
        <div class="funtion">
          <el-form :inline="true">
            <el-form-item label="模板编号">
              <el-input
                v-model="get_discount_coupon_template_info_list.keywordNumber"
                placeholder="请输入模板编号"
                clearable
                @keyup.enter.native="getDiscountCouponTemplateInfoList"
              />
            </el-form-item>
            <el-form-item label="模板名称">
              <el-input
                v-model="get_discount_coupon_template_info_list.keywordName"
                placeholder="请输入模板名称"
                clearable
                @keyup.enter.native="getDiscountCouponTemplateInfoList"
              />
            </el-form-item>
          </el-form>
        </div>

        <el-table
          :data="data_discount_coupon_template_info_list.data"
          class="table"
          highlight-current-row
          height="410px"
          max-height="410px"
          @selection-change="getInnerSelection"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="discount_coupon_template_number" label="模板编号" />
          <el-table-column prop="name" label="模板名称" />
          <el-table-column prop="subhead" label="模板副标题" />
          <el-table-column prop="type" label="模板类型">
            <template slot-scope="{ row }">
              <span>{{ type[row.type] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="优惠方式">
            <template slot-scope="{ row }">
              <span v-if="row.type === 0">{{ '满'+row.full_price+'减'+row.subtract_price }}</span>
              <span v-if="row.type === 1">{{ '满'+row.full_price+'折'+row.discount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户类型">
            <template slot-scope="{ row }">
              <span>{{ user_type[row.user_type] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否优惠码">
            <template slot-scope="{ row }">
              <span>{{ is_not[row.is_promotion_code] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效期">
            <template slot-scope="{ row }">
              <span v-if="row.is_fixed_date === 0">{{ '自领取日起'+row.expiry_day+'天' }}</span>
              <span v-if="row.is_fixed_date === 1">{{ row.commencement_date+' - '+row.expiry_date }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          class="pagination"
          background
          layout="total, sizes,prev, pager, next, jumper"
          :total="data_discount_coupon_template_info_list.total"
          :page-size="get_discount_coupon_template_info_list.pageSize"
          :page-sizes="[20, 50, 100]"
          :current-page="get_discount_coupon_template_info_list.currentPage"
          @size-change="innerChangePageSize"
          @current-change="innerChangeCurrentPage"
        />
        <!-- 分页 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDiscountCouponTemplateInnerDialog = false">取 消</el-button>
          <el-button type="primary" @click="addDiscountCouponTemplate">确 定</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDiscountCouponActivityDialog = false">取 消</el-button>
        <el-button type="primary" @click="changeDiscountCouponActivityInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增/修改活动信息dialog -->

    <!-- 优惠券库存管理dialog -->
    <el-dialog
      title="优惠券库存管理"
      :visible.sync="discountCouponInventoryDialog"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-table
        v-loading="dialogDataRequestLoading"
        element-loading-text="正在加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        :data="data_discount_coupon_template"
        class="table"
        highlight-current-row
        :height="tableHeight"
        :max-height="tableHeight"
      >
        <el-table-column label="模板编号及名称">
          <template slot-scope="{ row }">
            <span>{{ '['+row.discount_coupon_template_number+'] '+row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="优惠券类型">
          <template slot-scope="{ row }">
            <span>{{ type[row.type] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="优惠券方式">
          <template slot-scope="{ row }">
            <span v-if="row.type === 0">{{ '满 '+row.full_price+' 减 '+row.subtract_price+' 元' }}</span>
            <span v-if="row.type === 1">{{ '满 '+row.full_price+' 折 '+row.discount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="surplus_num" label="库存剩余" />
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="success" @click.stop="addInventory(row)">添加库存</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 优惠券库存管理dialog -->

    <!-- 剪切图片dialog -->
    <el-dialog title="图片剪裁" :visible.sync="UploadPathDialog" :close-on-click-modal="false">
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :info="option.info"
            :output-size="option.size"
            :output-type="option.outputType"
            :can-scale="option.canScale"
            :auto-crop="option.autoCrop"
            :auto-crop-width="option.autoCropWidth"
            :auto-crop-height="option.autoCropHeight"
            :fixed-box="option.fixedBox"
            :fixed="option.fixed"
            :fixed-number="option.fixedNumber"
            :full="option.full"
            :can-move-box="option.canMoveBox"
            :original="option.original"
            :center-box="option.centerBox"
            :info-true="option.infoTrue"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="UploadPathDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="uploadImageLoading" @click="upLoadImage">确认</el-button>
      </div>
    </el-dialog>
    <!-- 剪切图片dialog -->
  </div>
</template>

<script>
import { getFormData, getDatatime } from '@/common/js/until'
import { uploadImage } from '@/api/upload'
import
{ getDiscountCouponActivityInfoList,
  changeDiscountCouponActivityShow,
  getDiscountCouponActivityTemplateInfo,
  changeDiscountCouponActivityInfo,
  addDiscountCouponInventory,
  deleteDiscountCouponInfo
} from '@/api/coupon-activity'
import { getDiscountCouponTemplateInfoList } from '@/api/coupon-template'

export default {
  data() {
    return {
      // table高度自适应
      tableHeight: window.innerHeight - 264,

      // loading开关
      dataRequestLoading: false,
      dialogDataRequestLoading: false,

      datePicker: [],

      // 按钮开关
      showDisabled: true,
      notShowDisabled: true,

      // dialog开关
      changeDiscountCouponActivityDialog: false,
      UploadPathDialog: false,
      addDiscountCouponTemplateInnerDialog: false,
      discountCouponInventoryDialog: false,

      // loading开关
      uploadImageLoading: false,

      // 展示图片
      show_path: '',
      show_cover_path: '',
      image_type: '',

      // 图片裁剪框
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 750, // 默认生成截图框宽度
        autoCropHeight: 1334, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [750, 1334], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: false, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },

      // 显示活动触发条件
      condition_type: {
        0: '新用户注册',
        1: '云打印下单付款',
        2: '需求订单下单付款',
        3: '朋友首单下单付款',
        4: '用户领取'
      },

      // 活动触发条件选择器
      condition_type_select: [
        { value: 0, label: '新用户注册' },
        { value: 1, label: '云打印下单付款' },
        { value: 2, label: '需求订单下单付款' },
        { value: 3, label: '朋友首单下单付款' },
        { value: 4, label: '用户领取' }
      ],

      // 是/否显示
      is_show: {
        0: '隐藏',
        1: '显示'
      },

      // 显示活动状态
      status: [
        { color: 'warning', label: '未开始', value: 0 },
        { color: 'success', label: '进行中', value: 1 },
        { color: 'info', label: '已结束', value: 2 }
      ],

      // 显示优惠券类型
      type: {
        0: '立减券',
        1: '折扣券'
      },

      // 显示用户类型
      user_type: {
        0: '新用户',
        1: '老用户'
      },

      // 显示是/否
      is_not: {
        0: '否',
        1: '是'
      },

      // filter数组
      filterConditionType: [
        { text: '新用户注册', value: 0 },
        { text: '云打印下单付款', value: 1 },
        { text: '需求订单下单付款', value: 2 },
        { text: '朋友首单下单付款', value: 3 },
        { text: '用户领取', value: 4 }
      ],

      filterStatus: [
        { text: '未开始', value: 0 },
        { text: '进行中', value: 1 },
        { text: '已结束', value: 2 }
      ],

      // 发起查询请求参数
      get_discount_coupon_activity_info_list: {
        pageSize: 20,
        currentPage: 1,
        keyword: '',
        keywordType: 0,
        sort_name: '',
        sort: 'desc',
        areaId: '',
        filterConditionType: '',
        filterStatus: '',
        filterIsShow: ''
      },

      // 查询返回值
      data_discount_coupon_activity_info_list: {
        data: [],
        filterArea: [],
        area: [],
        total: 0
      },

      // 发起查询优惠券模板信息参数
      get_discount_coupon_template_info_list: {
        pageSize: 20,
        currentPage: 1,
        keywordNumber: '',
        keywordName: '',
        sort_name: '',
        sort: 'desc',
        type: [0, 1],
        is_promotion_code: [0, 1],
        user_type: [0, 1],
        is_fixed_date: [0, 1],
        exclude: []
      },

      // 查询优惠券模板信息返回值
      data_discount_coupon_template_info_list: {
        data: [],
        total: 0
      },

      // 新增/修改活动信息dialog标题
      change_discount_coupon_activity_info_title: '',

      // 新增/修改活动信息参数
      change_discount_coupon_activity_info: {
        discount_coupon_activity_id: '',
        area_id: '',
        area_number: '',
        area_name: '',
        discount_coupon_template_id: [],
        condition_type: '',
        title: '',
        intro: '',
        cover_path: '',
        path: '',
        coupon_color: '',
        rule: '',
        status: 0,
        is_show: '',
        start_date: '',
        end_date: '',
        create_time: ''
      },

      // 优惠券模板数组
      data_discount_coupon_template: [],
      bug: [1],

      // 绑定优惠活动id
      discount_coupon_activity_id: '',

      // 绑定优惠活动模板数组
      discount_coupon_template_id_arr: [],

      // 表单校验规则
      rules: {
        input: { required: true, message: '请完成输入！', trigger: 'blur' },
        select: { required: true, message: '请完成选择！', trigger: 'blur' },
        image: { required: true, message: '请上传图片！', trigger: 'blur' }
      }
    }
  },
  mounted() {
    this.getDiscountCouponActivityInfoList() // 查询优惠活动信息列表
  },
  methods: {
    // 图片地址拼接
    getPath() {
      return process.env.VUE_APP_BASE_API
    },
    // 查询优惠活动信息列表
    getDiscountCouponActivityInfoList() {
      this.dataRequestLoading = true
      getDiscountCouponActivityInfoList(this.get_discount_coupon_activity_info_list).then(res => {
        res.result.showing.forEach(val => {
          val['discount_coupon_template_id'] = JSON.parse(val['discount_coupon_template_id'])
        })
        this.data_discount_coupon_activity_info_list = {
          data: res.result.showing,
          filterArea: res.result.filterArea,
          area: res.result.area,
          total: res.result.total
        }
        this.dataRequestLoading = false
      })
    },

    // 显示优惠券状态
    status_text(data) {
      const status = this.status.filter(v => {
        if (v.value === data) {
          return v.label
        }
      })
      return status[0].label
    },

    // 显示优惠券状态颜色
    status_color(data) {
      const status = this.status.filter(v => {
        if (v.value === data) {
          return v.color
        }
      })
      return status[0].color
    },

    // 打开新增优惠活动界面
    openAddDiscountCouponActivityDialog() {
      this.change_discount_coupon_activity_info_title = '新增活动信息'
      this.change_discount_coupon_activity_info = {
        discount_coupon_activity_id: '',
        area_id: '',
        area_number: '',
        area_name: '',
        discount_coupon_template_id: [],
        condition_type: '',
        title: '',
        intro: '',
        cover_path: '',
        path: '',
        coupon_color: '',
        rule: '',
        status: 0,
        is_show: 1,
        start_date: '',
        end_date: '',
        create_time: ''
      }
      this.datePicker = []
      this.show_path = ''
      this.show_cover_path = ''
      this.data_discount_coupon_template = []
      this.get_discount_coupon_template_info_list.exclude = []
      getDiscountCouponTemplateInfoList(this.get_discount_coupon_template_info_list).then(res => {
        this.data_discount_coupon_template_info_list = {
          data: res.result.showing,
          total: res.result.total
        }
      })
      this.changeDiscountCouponActivityDialog = true
    },

    // 处理活动期限
    changePickTime() {
      this.change_discount_coupon_activity_info.start_date = getDatatime(this.datePicker[0])
      this.change_discount_coupon_activity_info.end_date = getDatatime(this.datePicker[1])
    },

    // 打开修改优惠活动界面
    openEditDiscountCouponActivityDialog(row) {
      this.change_discount_coupon_activity_info_title = '修改活动信息'
      this.change_discount_coupon_activity_info = {
        discount_coupon_activity_id: row.discount_coupon_activity_id,
        area_id: row.area_id,
        area_number: row.area_number,
        area_name: row.area_name,
        discount_coupon_template_id: row.discount_coupon_template_id,
        condition_type: row.condition_type,
        title: row.title,
        intro: row.intro,
        cover_path: row.cover_path,
        path: row.path,
        coupon_color: row.coupon_color,
        rule: row.rule,
        status: row.status,
        is_show: row.is_show,
        start_date: row.start_date,
        end_date: row.end_date,
        create_time: row.create_time
      }
      this.show_path = process.env.VUE_APP_BASE_API + row.path
      this.show_cover_path = process.env.VUE_APP_BASE_API + row.cover_path
      getDiscountCouponActivityTemplateInfo({ discount_coupon_activity_id: row.discount_coupon_activity_id, discount_coupon_template_id: row.discount_coupon_template_id }).then(res => {
        this.data_discount_coupon_template = res.result
        this.get_discount_coupon_template_info_list.exclude = row.discount_coupon_template_id
        getDiscountCouponTemplateInfoList(this.get_discount_coupon_template_info_list).then(res => {
          this.data_discount_coupon_template_info_list = {
            data: res.result.showing,
            total: res.result.total
          }
        })
      })
      this.changeDiscountCouponActivityDialog = true
    },

    // 新增/修改优惠活动信息
    changeDiscountCouponActivityInfo() {
      changeDiscountCouponActivityInfo(this.change_discount_coupon_activity_info).then(res => {
        this.getDiscountCouponActivityInfoList()
        this.changeDiscountCouponActivityDialog = false
      })
    },

    // 打开库存管理界面
    openDiscountCouponInventoryDialog(row) {
      this.dialogDataRequestLoading = true
      this.discountCouponInventoryDialog = true
      this.discount_coupon_activity_id = row.discount_coupon_activity_id
      this.discount_coupon_template_id_arr = row.discount_coupon_template_id
      getDiscountCouponActivityTemplateInfo({ discount_coupon_activity_id: row.discount_coupon_activity_id, discount_coupon_template_id: row.discount_coupon_template_id }).then(res => {
        this.data_discount_coupon_template = res.result
        this.dialogDataRequestLoading = false
      })
    },

    // 添加优惠券库存
    addInventory(row) {
      this.$prompt('请输入库存数', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'number'
      }).then(({ value }) => {
        addDiscountCouponInventory({
          discount_coupon_template_id: row.discount_coupon_template_id,
          discount_coupon_activity_id: this.discount_coupon_activity_id,
          total: value
        }).then(res => {
          getDiscountCouponActivityTemplateInfo({
            discount_coupon_activity_id: this.discount_coupon_activity_id,
            discount_coupon_template_id: this.discount_coupon_template_id_arr
          }).then(res => {
            this.data_discount_coupon_template = res.result
            this.discountCouponInventoryDialog = true
          })
        })
        this.$message({
          type: 'success',
          message: '已成功增加库存' + value
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },

    // 批量显示/隐藏优惠活动
    changeDiscountCouponActivityShow(data) {
      this.$confirm('此操作将改变所选中的优惠活动显示状态，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = []
        this.selection.forEach(val => {
          arr.push(val.discount_coupon_activity_id)
        })
        changeDiscountCouponActivityShow({ is_show: data, discount_coupon_activity_id: arr }).then(res => {
          this.getDiscountCouponActivityInfoList()
          this.$notify({
            title: '成功',
            message: '修改优惠活动显示状态成功！',
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' })
      })
    },

    // 批量删除优惠活动信息
    deleteDiscountCouponInfo() {
      this.$confirm('此操作将删除所选中的优惠活动，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = []
        this.selection.forEach(val => {
          arr.push(val.discount_coupon_activity_id)
        })
        deleteDiscountCouponInfo({ discount_coupon_activity_id: arr }).then(res => {
          this.getDiscountCouponActivityInfoList()
          this.$notify({
            title: '成功',
            message: '删除优惠券活动信息成功！',
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' })
      })
    },

    // 获取选择项
    getSelection(selection) {
      if (selection.length === 0) {
        this.showDisabled = true
        this.notShowDisabled = true
      } else {
        this.showDisabled = false
        this.notShowDisabled = false
      }
      this.selection = selection
    },

    // 确认添加优惠券模板
    addDiscountCouponTemplate() {
      this.innerSelection.forEach(val => {
        this.data_discount_coupon_template.push(val)
        this.change_discount_coupon_activity_info.discount_coupon_template_id.push(val.discount_coupon_template_id)
      })
      this.bug.push(1)
      this.addDiscountCouponTemplateInnerDialog = false
    },

    // 本地删除优惠券模板
    localDeleteDiscountCouponTemplate(data) {
      const number = this.data_discount_coupon_template.indexOf(data)
      this.data_discount_coupon_template.splice(number, 1)
      this.change_discount_coupon_activity_info.discount_coupon_template_id.splice(number, 1)
    },

    // 获取内层选择项
    getInnerSelection(selection) {
      this.innerSelection = selection
    },

    // 切换每页条数方法
    changePageSize(data) {
      this.get_discount_coupon_activity_info_list.pageSize = data
      this.getDiscountCouponActivityInfoList()
    },

    // 切换页码方法
    changeCurrentPage(data) {
      this.get_discount_coupon_activity_info_list.currentPage = data
      this.getDiscountCouponActivityInfoList()
    },

    // 切换内层每页条数方法
    innerChangePageSize(data) {
      this.get_discount_coupon_template_info_list.pageSize = data
      this.getDiscountCouponTemplateInfoList()
    },

    // 切换内层页码方法
    innerChangeCurrentPage(data) {
      this.get_discount_coupon_template_info_list.currentPage = data
      this.getDiscountCouponTemplateInfoList()
    },

    // 筛选记录者
    changefilter(filters) {
      if (filters.areaId) {
        if (filters.areaId.length === 0) {
          this.get_discount_coupon_activity_info_list.areaId = ''
        } else {
          this.get_discount_coupon_activity_info_list.areaId = filters.areaId[0]
        }
      } else if (filters.filterConditionType) {
        if (filters.filterConditionType.length === 0) {
          this.get_discount_coupon_activity_info_list.filterConditionType = ''
        } else {
          this.get_discount_coupon_activity_info_list.filterConditionType = filters.filterConditionType[0]
        }
      } else if (filters.filterStatus) {
        if (filters.filterStatus.length === 0) {
          this.get_discount_coupon_activity_info_list.filterStatus = ''
        } else {
          this.get_discount_coupon_activity_info_list.filterStatus = filters.filterStatus[0]
        }
      } else if (filters.filterIsShow) {
        if (filters.filterIsShow.length === 0) {
          this.get_discount_coupon_activity_info_list.filterIsShow = ''
        } else {
          this.get_discount_coupon_activity_info_list.filterIsShow = filters.filterIsShow[0]
        }
      }
      this.getDiscountCouponActivityInfoList()
    },

    // 排序
    changeSort({ column, order }) {
      if (column.columnKey === 'create_time') {
        switch (order) {
          case 'descending':
            this.get_discount_coupon_activity_info_list.sort_name = 'create_time'
            this.get_discount_coupon_activity_info_list.sort = 'desc'
            this.getDiscountCouponActivityInfoList()
            break
          case 'ascending':
            this.get_discount_coupon_activity_info_list.sort_name = 'create_time'
            this.get_discount_coupon_activity_info_list.sort = 'asc'
            this.getDiscountCouponActivityInfoList()
            break
          default:
            this.get_discount_coupon_activity_info_list.sort_name = ''
            this.get_discount_coupon_activity_info_list.sort = 'desc'
            this.getDiscountCouponActivityInfoList()
        }
      }
    },

    // 打开剪切界面背景图
    changeUploadImage(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 2
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        fileList.pop()
        return false
      }

      if (file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
        this.$message.error('上传图片只支持jpeg和png!')
        fileList.pop()
        return false
      }
      // 将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        fileList.pop()
        this.option.img = URL.createObjectURL(file.raw)
        this.option.fixedNumber = [750, 1334]
        this.image_type = 1
        this.UploadPathDialog = true
      })
    },
    // 打开剪切界面封面图
    changeCoverUploadImage(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 2
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        fileList.pop()
        return false
      }

      if (file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
        this.$message.error('上传图片只支持jpeg和png!')
        fileList.pop()
        return false
      }
      // 将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        fileList.pop()
        this.option.img = URL.createObjectURL(file.raw)
        this.option.fixedNumber = [1, 1]
        this.image_type = 2
        this.UploadPathDialog = true
      })
    },
    // 上传剪切后的图片背景图
    upLoadImage() {
      this.$refs.cropper.getCropBlob(data => {
        const formData = getFormData(data, 'discount_coupon_activity')
        uploadImage(formData).then(res => {
          if (this.image_type === 1) {
            this.change_discount_coupon_activity_info.path = res.result
            this.show_path = process.env.VUE_APP_BASE_API + res.result
          } else {
            this.change_discount_coupon_activity_info.cover_path = res.result
            this.show_cover_path = process.env.VUE_APP_BASE_API + res.result
          }
          this.UploadPathDialog = false
        })
      })
    }
  }
}
</script>
